package com.wx.arrays_;

import com.wx.javacode.modifier.A;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @Author : 佩萁
 * Description :
 * @Create : 2023/7/24 - 16:30
 */
public class ArrayExercise {
    public static void main(String[] args) {
     /*
        案例： 自定义 Book 类，里面包含 name 和 price ，按 price 排序(从大到小)。
        要求使用两种方式排序 ,  有一个 Book[] books = 4 本书对象.

        使用前面学习过的传递 实现 Comparator 接口匿名内部类，也称为定制排序。
        [同学们完成这个即可 10min    ],
        可以按照 price ( 1)从大到小 (2)从小到大 (3)  按照书名长度从大到小
        */
        Book[] books = new Book[4];
        books[0] = new Book("金瓶梅", 100);
        books[2] = new Book("青年文摘", 5);
        books[1] = new Book("金瓶梅新", 90);
        books[3] = new Book("Java从入门到放弃", 300);
        Arrays.sort(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book book1 = (Book) o1;
                Book book2 = (Book) o2;
                double priceVal = book1.getPrice() - book2.getPrice();
                if (priceVal > 0) {
                    return -1;
                } else if (priceVal < 0) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println(Arrays.toString(books));

        Arrays.sort(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book book1 = (Book) o1;
                Book book2 = (Book) o2;
                return book1.getName().length() - book2.getName().length();
            }
        });
        System.out.println(Arrays.toString(books));
    }
}

class Book {
    private String name;
    private double price;

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
